package com.springboot.demo.configures;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.util.Map;

/**
 * 因无法用@value读取application配置文件的值,此改为构造器手动赋值
 * mybatis集成配置类
 * @author 18103
 * @Date 2018/12/19
 * @Description
 */
@Configuration
public class MybatisConfigure{

    private String typeAliasesPackage;
    private String mapperLocations;
    private String configLocation;
    private String basePackage;

    public MybatisConfigure() throws Exception{
        Yaml yaml=new Yaml();
        Map<String,Object> map=yaml.load(new FileInputStream(ResourceUtils.getFile("classpath:application.yml")));
        Map<String,String> demo=(Map<String, String>) map.get("demo");
        typeAliasesPackage=demo.get("typeAliasesPackage");
        mapperLocations=demo.get("mapperLocations");
        configLocation=demo.get("configLocation");
        basePackage=demo.get("basePackage");
        System.out.println("name:"+demo.get("name"));
    }



    //sqlsession工厂
    @Order
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource)throws Exception{
        SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(dataSource);
        //mybatis 扫描包
        factoryBean.setTypeAliasesPackage(typeAliasesPackage);
        ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
        //mybatis mapper 扫描
        factoryBean.setMapperLocations(resolver.getResources(mapperLocations));
        //加载全局的配置文件
        factoryBean.setConfigLocation(resolver.getResource(configLocation));
        return factoryBean.getObject();
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //设置sqlsession
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        //设置扫描自动扫描mapper包路径
        mapperScannerConfigurer.setBasePackage(basePackage);
        return mapperScannerConfigurer;
    }

}